# -*- coding: utf-8 -*-

import glob
import string
import re
import d15n_routines as r
from salt_file import salt

n = '\x0D\x0A'

if 1: # calculate sha256 digests

    for f in glob.glob('_cleanup_POC_ID_birthnumber_decline_v3.csv'):

        i = open(f, 'r')
        o = open('_d15n_final' + f, 'wb')
        o.write('ID\tICO_RC_birthdate\tbn_length\tICO_RC_appendix_d15n' + n)

        for l in i.readlines():

            l = r.remove_eol(l)

            id, bn = string.split(l, '\t')
            bn_len = len(bn)

            bn_date = ''; bn_appendix = ''
            if bn_len in (7, 8, 9, 10, 11, 12):
                bn_date = bn[:6]
                bn_appendix = r.sha256(bn[6:] + salt)
            elif bn_len == 6:
                bn_date = bn[:6]
            elif bn in ('#ND'):
                bn_date = '#ND'
                bn_len = ''
            elif bn in ('.'):
                bn_date = '.'
                bn_len = ''
            elif bn in (';'):
                bn_date = ';'
                bn_len = ''
            else:
                print bn,

            #test run
            #final run ... original line (l) and bn ommited
            res = "%s\t%s\t%s\t%s" % (id, bn_date, str(bn_len),bn_appendix) + n

            o.write(res)
        o.close()
